package com.framemodule.base;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.PopupWindow;

import com.framemodule.BaseApp.AppManager;
import com.framemodule.BaseApp.BaseApp;
import com.framemodule.R;
import com.framemodule.base.netstatus.NetChangeObserver;
import com.framemodule.base.netstatus.NetStateReceiver;
import com.framemodule.base.netstatus.NetUtils;
import com.framemodule.utils.Logger;
import com.kymjs.frame.view.IDelegate;


import java.util.ArrayList;

import cn.bingoogolapple.refreshlayout.BGANormalRefreshViewHolder;
import cn.bingoogolapple.refreshlayout.BGARefreshLayout;
import cn.bingoogolapple.refreshlayout.BGARefreshViewHolder;

/**
 * Created by User on 2015/12/14.
 */
public abstract class BaseActivityPresenter<T extends IDelegate> extends ActivityPresenter<T> {
    protected String token = "";//用于对比判断是否登陆状态有变化
    /**
     * network status
     */
    protected NetChangeObserver mNetChangeObserver = null;
    protected ProgressDialog mLoadingDialog;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        token = BaseApp.getSharedInstance().loadString("token");
        Logger.e(this.getClass().getSimpleName());
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        // 将该Activity加入堆栈
        AppManager.getAppManager().addActivity(this);
        initModel();
        mNetChangeObserver = new NetChangeObserver() {
            @Override
            public void onNetConnected(NetUtils.NetType type) {
                super.onNetConnected(type);
                onNetworkConnected(type);
            }

            @Override
            public void onNetDisConnect() {
                super.onNetDisConnect();
                onNetworkDisConnected();
            }
        };
        NetStateReceiver.registerObserver(mNetChangeObserver);
        NetStateReceiver.registerNetworkStateReceiver(this);

        mLoadingDialog = new ProgressDialog(this);
        mLoadingDialog.setCanceledOnTouchOutside(false);


    }


    @Override
    protected void onResume() {
        super.onResume();
//        if (BaseApp.getSharedInstance() != null && !token.equals(BaseApp.getSharedInstance().loadString("token"))) {//判断登陆状态是否变化
//            token = BaseApp.getSharedInstance().loadString("token");
//            refresh();//刷新此activity
//            return;
//        }
        BaseApp.handler = basehandler;

    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {

        new Thread(new Runnable() {
            @Override
            public void run() {
//                OkHttpClientManager.getInstance().cancelTag(this);//getApplicationContext()
            }
        }).start();
        NetStateReceiver.removeRegisterObserver(mNetChangeObserver);
        // 将该Activity从堆栈移除
        AppManager.getAppManager().removeActivity(this);
        super.onDestroy();
    }

    /**
     * startActivity
     *
     * @param clazz
     */
    protected void readyGo(Class<?> clazz) {
        Intent intent = new Intent(this, clazz);
        startActivity(intent);
    }

    /**
     * startActivity
     *
     * @param clazz
     */
    protected void readyGoSingle(Class<?> clazz) {
        Intent intent = new Intent(this, clazz);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity(intent);
        finish();
    }

    /**
     * startActivity
     *
     * @param clazz
     */
    protected void readyGoSingle(Class<?> clazz, Bundle bundle) {
        Intent intent = new Intent(this, clazz);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        if (null != bundle) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
        finish();
    }

    /**
     * startActivity with bundle
     *
     * @param clazz
     * @param bundle
     */
    protected void readyGo(Class<?> clazz, Bundle bundle) {
        Intent intent = new Intent(this, clazz);
        if (null != bundle) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

    /**
     * startActivity then finish
     *
     * @param clazz
     */
    protected void readyGoThenKill(Class<?> clazz) {
        Intent intent = new Intent(this, clazz);
        if (!"LoadActivity".equals(clazz.getSimpleName())) {
            finish();
        } else {
            if (token.equals("")) {

            } else {
                intent.putExtra("LOOK", "LOOK");
//                BaseApp.getSharedInstance().clear();
            }
        }
        startActivity(intent);
    }

    /**
     * startActivity with bundle then finish
     *
     * @param clazz
     * @param bundle
     */
    protected void readyGoThenKill(Class<?> clazz, Bundle bundle) {
        Intent intent = new Intent(this, clazz);
        if (null != bundle) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
        finish();
    }

    /**
     * startActivityForResult
     *
     * @param clazz
     * @param requestCode
     */
    protected void readyGoForResult(Class<?> clazz, int requestCode) {
        Intent intent = new Intent(this, clazz);
        startActivityForResult(intent, requestCode);
    }

    /**
     * startActivityForResult with bundle
     *
     * @param clazz
     * @param requestCode
     * @param bundle
     */
    protected void readyGoForResult(Class<?> clazz, int requestCode, Bundle bundle) {
        Intent intent = new Intent(this, clazz);
        if (null != bundle) {
            intent.putExtras(bundle);
        }
        startActivityForResult(intent, requestCode);
    }

    /**
     * 初始化model对象
     */
    protected abstract void initModel();

    /**
     * 网络连接可用的时候
     */
    protected abstract void onNetworkConnected(NetUtils.NetType type);

    /**
     * 网络不可用的时候
     */
    protected abstract void onNetworkDisConnected();

    public Handler basehandler = new Handler() {
        @Override
        public void handleMessage(final Message msg) {
            switch (msg.what) {
                case 0://收到邀请
                    break;
                case 1:
                    break;
                case 2://没有结束直播
                    break;
                case 3://在直播或观看界面
                    break;
                case 4://私信消息 跳转主页
                    break;
                case 5://系统私信消息
                    break;
                case 6:
                    showNetPop();
                    break;
                case 7:
                    closeNetPop();
                    break;
                case 8://话题邀请
                    break;
            }
        }
    };

    private void closeNetPop() {
        if (netPop != null) {
            netPop.dismiss();
        }
    }

    private PopupWindow netPop;

    private void showNetPop() {
        getNetPopupWindow();
        if (netPop != null) {
            netPop.showAtLocation(viewDelegate.getRootView(), Gravity.TOP, 0, 0);
            TranslateAnimation translateAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, -1, Animation.RELATIVE_TO_SELF, 0);
            translateAnimation.setDuration(500);
            translateAnimation.setFillAfter(true);
            netView.findViewById(R.id.rl_net).setAnimation(translateAnimation);
            netView.findViewById(R.id.rl_net).startAnimation(translateAnimation);
        }
    }

    private void getNetPopupWindow() {
        if (null != netPop) {
            netPop.dismiss();
            return;
        } else {
            initNetPopuptWindow();
        }
    }

    private View netView;

    private void initNetPopuptWindow() {
        netView = View.inflate(this, R.layout.pop_net, null);
        netPop = new PopupWindow(netView, FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT);
        netPop.setFocusable(false);
        netView.findViewById(R.id.rl_net).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(android.provider.Settings.ACTION_SETTINGS));
            }
        });

    }


    /**
     * 进入的时候展示引导图，只在第一次的进入的时候展示
     *
     * @param name           //引导图展示的
     * @param imageSourceIds //引导图的source id
     */
    public void showGuide(String name, int... imageSourceIds) {
        if (imageSourceIds == null) {
            return;
        }
        if (imageSourceIds.length == 0) {
            return;
        }

        boolean isFirstIn = BaseApp.getMySharedInstance().loadBoolean(name, true);
        if (isFirstIn) {
            ArrayList<Integer> imageGuides = new ArrayList<>();
            for (int imageSourceId : imageSourceIds) {
                imageGuides.add(imageSourceId);
            }
            Bundle bundle = new Bundle();
            bundle.putIntegerArrayList("imageGuides", imageGuides);
//            readyGo(GuideActivity.class, bundle);
            BaseApp.getMySharedInstance().saveBoolean(name, false);
        }

    }

    /**
     * 刷新此activity
     */
    protected void refresh() {
        startActivity(getIntent());
        finish();
    }

    public void initRefreshLayout(BGARefreshLayout mRefreshLayout, BGARefreshLayout.BGARefreshLayoutDelegate delegate) {
        // 为BGARefreshLayout 设置代理
        mRefreshLayout.setDelegate(delegate);
        // 设置下拉刷新和上拉加载更多的风格     参数1：应用程序上下文，参数2：是否具有上拉加载更多功能
        BGARefreshViewHolder refreshViewHolder = new BGANormalRefreshViewHolder(this, true);
        // 设置下拉刷新和上拉加载更多的风格
        mRefreshLayout.setRefreshViewHolder(refreshViewHolder);


        // 为了增加下拉刷新头部和加载更多的通用性，提供了以下可选配置选项  -------------START
        // 设置正在加载更多时不显示加载更多控件
        // mRefreshLayout.setIsShowLoadingMoreView(false);
        // 设置正在加载更多时的文本
        refreshViewHolder.setLoadingMoreText("加载更多");
        // 设置整个加载更多控件的背景颜色资源 id
        refreshViewHolder.setLoadMoreBackgroundColorRes(R.color.gray);
        // 设置整个加载更多控件的背景 drawable 资源 id
        //refreshViewHolder.setLoadMoreBackgroundDrawableRes(loadMoreBackgroundDrawableRes);
        // 设置下拉刷新控件的背景颜色资源 id
        //refreshViewHolder.setRefreshViewBackgroundColorRes(refreshViewBackgroundColorRes);
        // 设置下拉刷新控件的背景 drawable 资源 id
        //refreshViewHolder.setRefreshViewBackgroundDrawableRes(refreshViewBackgroundDrawableRes);
        // 设置自定义头部视图（也可以不用设置）     参数1：自定义头部视图（例如广告位）， 参数2：上拉加载更多是否可用
        //mRefreshLayout.setCustomHeaderView(mBanner, false);
        // 可选配置  -------------END
    }

    public void initRefreshLayout(BGARefreshLayout mRefreshLayout, BGARefreshLayout.BGARefreshLayoutDelegate delegate, View customHeaderView) {
        // 为BGARefreshLayout 设置代理
        mRefreshLayout.setDelegate(delegate);
        // 设置下拉刷新和上拉加载更多的风格     参数1：应用程序上下文，参数2：是否具有上拉加载更多功能
        BGARefreshViewHolder refreshViewHolder = new BGANormalRefreshViewHolder(this, true);
        // 设置下拉刷新和上拉加载更多的风格
        mRefreshLayout.setRefreshViewHolder(refreshViewHolder);


        // 为了增加下拉刷新头部和加载更多的通用性，提供了以下可选配置选项  -------------START
        // 设置正在加载更多时不显示加载更多控件
        // mRefreshLayout.setIsShowLoadingMoreView(false);
        // 设置正在加载更多时的文本
        refreshViewHolder.setLoadingMoreText("加载更多");
        // 设置整个加载更多控件的背景颜色资源 id
        refreshViewHolder.setLoadMoreBackgroundColorRes(R.color.gray);
        // 设置整个加载更多控件的背景 drawable 资源 id
        //refreshViewHolder.setLoadMoreBackgroundDrawableRes(loadMoreBackgroundDrawableRes);
        // 设置下拉刷新控件的背景颜色资源 id
        //refreshViewHolder.setRefreshViewBackgroundColorRes(refreshViewBackgroundColorRes);
        // 设置下拉刷新控件的背景 drawable 资源 id
        //refreshViewHolder.setRefreshViewBackgroundDrawableRes(refreshViewBackgroundDrawableRes);
        // 设置自定义头部视图（也可以不用设置）     参数1：自定义头部视图（例如广告位）， 参数2：上拉加载更多是否可用
        mRefreshLayout.setCustomHeaderView(customHeaderView, true);
        // 可选配置  -------------END
    }
}
